package cdms.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cdms.domain.Sender;

/**
 * 
 * check login status of senders
 * 
 * @author fengduxin
 * @version 1.0
 *
 */
public class SenderInterceptor implements HandlerInterceptor {
	
	private final static Log log = LogFactory.getLog(SenderInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception exception) throws Exception {

		log.debug("3.Called after rendering the view");

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView model)
			throws Exception {

		log.debug("2.Called after handler method request completion, before rendering the view");

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

		log.debug("1.Called before handler method");
		
		HttpSession session = request.getSession();
		Sender sender = (Sender) session.getAttribute("sender");
		
		if(sender != null && sender.getUserName() != null) {
			return true;
		}
		
		response.sendRedirect(request.getContextPath() + "/sender/login");
		return false;
	}

}
